<template>
	<view>
		<!-- 补充个人资料 -->
		<uni-section title="个人信息" type="line">
			<view class="example">
				<!-- 基础表单校验 -->
				<uni-forms ref="valiForm" :rules="rules" :model="valiFormData" labelWidth="80px">
					<uni-forms-item label="姓名" required name="name">
						<uni-easyinput v-model="valiFormData.name" placeholder="请输入姓名" />
					</uni-forms-item>
					
					<uni-forms-item label="电话" required name="mobile">
						<uni-easyinput v-model="valiFormData.mobile" placeholder="请输入电话号码" />
					</uni-forms-item>
					<uni-forms-item label="学校" required name="schoolId">
						<uni-data-picker :localdata="schoolData" v-model="valiFormData.schoolId" @change="pickSchool"   popup-title="选择学校">
							
						</uni-data-picker>
					</uni-forms-item>
					<!-- <uni-forms-item label="性别" >
						<uni-data-checkbox v-model="valiFormData.sex" :localdata="sexs" />
					</uni-forms-item> -->
					<uni-forms-item label="学号"  required name="studentNo" >
						<uni-easyinput v-model="valiFormData.studentNo" placeholder="请输入学号" />
					</uni-forms-item>
					<uni-forms-item label="身份证号"  name="idCard">
						<uni-easyinput v-model="valiFormData.idCard"  placeholder="请输入身份证号" />
					</uni-forms-item>
					<uni-forms-item label="入学年"  name="entryYear">
						<picker mode="date" fields="year" value="{{valiFormData.entryYear}}" :start="startDate" :end="endDate" @change="bindDateChange">
							 
							 <uni-easyinput :inputType="'text'"
						      v-model="valiFormData.entryYear"
						      @click="openPicker"></uni-easyinput>
						</picker>
						
					</uni-forms-item>
					<uni-forms-item label="院系名称"  name="facultyName">
						<uni-easyinput v-model="valiFormData.facultyName" placeholder="请输入院系名称" />
					</uni-forms-item>
					
					<uni-forms-item label="班级名称"  name="className">
						<uni-easyinput v-model="valiFormData.className" placeholder="请输入班级名称" />
					</uni-forms-item>
					<uni-forms-item label="住址"  name="address">
						<uni-easyinput v-model="valiFormData.address" placeholder="请输入住址" />
					</uni-forms-item>
					
					
					
				</uni-forms>
				<button type="primary" @click="submit('valiForm')">提交</button>
			</view>
		</uni-section>
	
	</view>
</template>

<script>
	import { mapMutations,mapState } from 'vuex'
	
	function getDate(type) {
		const date = new Date();
	
		let year = date.getFullYear();
	
		if (type === 'start') {
			year = year - 4
		} else if (type === 'end') {
			year = year ;
		}else if(type === "now"){
			year = year;
		}
	
		return `${year}级`;
	}
	export default {
		data() {
			return {
				// 校验表单数据
				valiFormData: {
					name: '',
					mobile: '',
					schoolId: '',
					sex: '',
					studentNo: '',
					idCard: '',
					entryYear: '',
					facultyName: '',
					className: '',
					address: '',
					
				},
				// 学校数据
				schoolData: [],
				// 校验规则
				rules: {
					name: {
						rules: [{
							required: true,
							errorMessage: '姓名不能为空'
						}]
					},
					mobile: {
						rules: [{
							required: true,
							errorMessage: '电话号码不能为空'
						}, {
							validateFunction: function(rule, value, data, callback) {
								let iphoneReg = (
									/^(13[0-9]|14[1579]|15[0-3,5-9]|16[6]|17[0123456789]|18[0-9]|19[89])\d{8}$/
								); //手机号码
								if (!iphoneReg.test(value)) {
									callback('手机号码格式不正确，请重新填写')
								}
							}
							
						}]
					},
					studentNo: {
						rules: [{
							required: true,
							errorMessage: '学号不能为空'
						}, {
							format: 'number',
							errorMessage: '学号只能输入数字'
						}]
					},
					schoolId: {
						rules: [{
							required: true,
							errorMessage: '学校不能为空'
						}]
					},
					idCard:{
						rules: [{
							required: false,
							errorMessage: '身份证号不能为空'
						},{
							validateFunction: function(rule, value, data, callback) {
								let reg1 = /^\d{15}$/;
								let reg2 = /^\d{17}(\d|X|x)$/;
								
								if (!(reg1.test(value) || reg2.test(value))) {
									callback('身份证格式不正确，请重新填写')
								}
							}
							
						}]
					}
					
				},
				// 请求参数对象
				queryObj: {
					// 页码值
					pageNo: 1,
					// 每页显示多少条数据
					pageSize: 10
				},
				// 单选数据源
				sexs: [{
					text: '男',
					value: 0
				}, {
					text: '女',
					value: 1
				}, {
					text: '保密',
					value: 2
				}],
				startDate:getDate('start'),
				endDate:getDate('end'),
				schoolDataServer: [],
				studentInfo: {},
				
			}
		},
		onLoad(options) {
			this.getSchoolList();
			this.getStudentInfo();
			
		},
		computed: {
		  ...mapState('m_user', ['userinfo']),
		  ...mapState('m_user', ['userId']),
		  ...mapState('m_dept', ['deptId']),
		  ...mapState('m_dept', ['dept']),
		  ...mapState('m_message', ['message']),
		},
		methods: {
			...mapMutations('m_dept', ['updateDeptInfo']),
			...mapMutations('m_user', ['updateUserInfo']),
			pickSchool(e){
				//将选择的学校放入内存中
				this.schoolDataServer.forEach((item)=>{
					if(item.deptId+"" ==e.detail.value[0].value){
						this.updateDeptInfo(item)
						this.valiFormData.schoolId = item.deptId+""
					}
					
				});
				
			},
			//验证身份证号
			 validateIdNumber(idNumber) {
			  var reg1 = /^\d{15}$/;
			  var reg2 = /^\d{17}(\d|X|x)$/;
			  return reg1.test(idNumber) || reg2.test(idNumber);
			},
			bindDateChange(e) {
			   this.valiFormData.entryYear = e.target.value;
			},
			openPicker() {
				// 打开选择器
				this.$refs.picker.open();
			},
			//验证身份证号e
			vaildId(e){
				var value=this.validateIdNumber(e);
				console.log(value)
			},
			
			//获取学校列表
			async getSchoolList(){
				await uni.request({
				    url: uni.$http.baseUrl+'/api/mobileDept/getSchoolList',
				    data: {
				       // 页码值
				       pageNo: this.queryObj.pageNo,
				       // 每页显示多少条数据
				       pageSize: this.queryObj.pageSize,
				    },
					method: 'POST',
				    header: {
				          // "Content-Type": "application/json",
				          "Content-Type": "application/x-www-form-urlencoded"
				        },
				    success: (res) => {
						 this.schoolDataServer=res.data.data
						var arr = []
						var i=0
						res.data.data.forEach((item)=>{
							arr.push({  text: item.name, value: ""+item.deptId ,id: i++})
						})
						this.schoolData=arr;
						
						this.valiFormData.schoolId=this.deptId+""
						
				    },
					fail: (res) =>{
						if (res.statusCode !== 200) return uni.$showMsg()
					}
				});
			},
			//获取学生信息
			async getStudentInfo(){
				await uni.request({
				    url: uni.$http.baseUrl+'/api/student/getStudentInfo',
				    data: {
				       // 学生id
				       id: this.userId,
				    },
					method: 'POST',
				    header: {
				          // "Content-Type": "application/json",
				          "Content-Type": "application/x-www-form-urlencoded"
				        },
				    success: (res) => {
						 this.studentInfo=res.data.data
						this.updateUserInfo(res.data.data)
						this.valiFormData.name=this.studentInfo.nickName
						this.valiFormData.mobile=this.studentInfo.mobile
						this.valiFormData.sex=this.studentInfo.sex
						this.valiFormData.studentNo=this.studentInfo.studentNo
						this.valiFormData.idCard=this.studentInfo.idCard
						this.valiFormData.entryYear=this.studentInfo.entryYear
						this.valiFormData.facultyName=this.studentInfo.facultyName
						this.valiFormData.className=this.studentInfo.className
						this.valiFormData.address=this.studentInfo.address
				    },
					fail: (res) =>{
						if (res.statusCode !== 200) return uni.$showMsg()
					}
				});
			},
			submit(ref) {
				console.log(this.valiFormData);
				this.$refs[ref].validate().then(res => {
					console.log('success', res);
					uni.showToast({
						title: `校验通过`
					})
					this.updateUserInfoToService(res)
					
					// 返回上一级页面
					uni.navigateBack();
				}).catch(err => {
					console.log('err', err);
				})
			},
			async updateUserInfoToService(res){
				await uni.request({
					url: uni.$http.baseUrl+'/api/student/update',
					method: 'POST',
					data: {
						id:this.userinfo.id,
							//昵称
						nickName: res.nickName,
						mobile: res.mobile,
						schoolId: res.schoolId,
						sex: res.sex,
						studentNo: res.studentNo,
						idCard: res.idCard,
						entryYear: res.entryYear,
						facultyName: res.facultyName,
						className: res.className,
						address: res.address,
					},
					header: {
						"Content-Type": "application/json",
						//"Content-Type": "application/x-www-form-urlencoded"
					},
					//sslVerify: false,
					success: (res1) => {
						console.log("更新用户数据----", res1.data.data);
					},
					fail: (res) =>{
						if (res.statusCode !== 200) return uni.$showMsg()
					},
				});
				
			},
		}
	}
</script>

<style>
.example {
		padding: 15px;
		background-color: #fff;
	}
</style>
